<template>
  <div class="container">
    <div class="content">
      <div v-for="(item, index) in list" :key="index">
      <el-form
        :model="item"
        :rules="rules"
        ref="ruleForm"
        class="demo-ruleForm"
      >
        <el-date-picker
          style="width: 260px"
          unlink-panels
          @change="
            (val) => {
              chooseTime(val, index);
            }
          "
          :clearable="false"
          v-model="item.data"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
        <el-form-item prop="number" class="d-inline">
          <el-input
            v-model="item.number"
            placeholder="请输入数字"
            style="width: 135px"
          ></el-input>
        </el-form-item>
      </el-form>
    </div>
    <div class="btn-container">
      <el-button
      size="medium"
      class="addBtn"
      @click="addDate(index)"
      >新增</el-button
    >
    </div>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: [
        {
          data: [],
          number: "",
        },
      ],
      rules: {
        number: [
          { required: true, message: "请输入数字", trigger: "blur" },
          {
            pattern: /^[-]?(\d{0,9})$/,
            message: "必须为整数,最大9位数(不含-号,支持正负数)",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    // 封装转换时间的函数
    returnTime(val) {
      return new Date(val).getTime() / 1000;
    },
    chooseTime(time, index) {
      let pickStart = this.returnTime(time[0]);
      let pickEnd = this.returnTime(time[1]);
      // 之前选择器选择的时间集合
      this.list.forEach((item, i) => {
        // 跟不是自己的时间进行比较
        if (index != i) {
          let start = this.returnTime(item.data[0]);
          // let end=item.data[1]
          let isTimeIn = pickStart <= start && start <= pickEnd;
          // 如果选择范围交叉就提示时间重叠,并清除用户所选时间
          if (isTimeIn) {
            this.$message.error("选择日期不能重叠!");
            this.list[index].data = "";
          }
        }
      });
    },
    addDate(index) {
      this.list.splice(index + 1, 0, { data: "", status: "" });
    },
  },
};
</script>
<style>
.el-date-editor .el-range-separator{
  width:15%
}
</style>
<style scoped>
.demo-ruleForm{
  margin-top:10px
}
.content{
  border-bottom: 2px solid #babaf2;
  box-sizing: border-box;
  padding:20px;
  width: 50%;
}
.container {
  margin: 20px;
}
.d-inline {
  display: inline-block;
}
.addBtn {
  color: #eba656;
}

</style>